import { reactive, toRefs, watch } from 'vue';
import { LocationQuery, useRoute } from 'vue-router';
import { DataObject } from '@/utils/types';
import { ToRefs } from '@vue/reactivity';

export interface Path {
  redirect: string;
  otherQuery: DataObject;
}

const getOtherQuery = (query: LocationQuery) => {
  return Object.keys(query).reduce((acc, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur];
    }
    return acc;
  }, {} as DataObject);
};

export const useQuery = (): ToRefs<Path> => {
  const route = useRoute();

  const query: Path = reactive({
    redirect: '/',
    otherQuery: {},
  });

  watch(
    () => route,
    to => {
      const source = to.query;
      if (query) {
        query.redirect = (source.redirect as string) ?? '/';
        query.otherQuery = getOtherQuery(source);
      }
    }
  );

  return {
    ...toRefs(query),
  };
};
